<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\admin\model\DistributeTask as DistributeTaskModer;
use app\admin\model\DistributeTaskLog;
use app\admin\model\PayConfig;
use app\admin\model\DistributeStatistics;
use app\admin\model\User;
use app\api\controller\Withdraw as WithdrawApi;
use app\admin\model\Payment;
use app\admin\model\Product;
use app\admin\model\ShopPriceLog;
use app\admin\model\Shop;
use app\admin\model\SArea;
use app\admin\model\UserAddress;
use app\admin\model\Withdraw;
use app\admin\model\DistributeTaskInvite;
use app\admin\model\ProductCategory;
use app\common\model\Config;
use think\Db;
use think\exception\PDOException;
use think\Exception;
use think\Session;

/**
 * 任务管理
 *
 * @icon   fa fa-list
 */
class DistributeTask extends Backend
{

    protected $model = null;
    protected $group_id = null;
    protected $admin = null;
    protected $categorylist = [];
    protected $noNeedRight = ['selectpage'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new DistributeTaskModer();
        $admin = Session::get('admin');
        $group_id = db('auth_group_access')->where(['uid'=>$admin['id']])->value('group_id');
        $this->group_id = $group_id;
        $this->admin = $admin;
        $this->assignconfig('group_id', $group_id);
        $this->view->assign('group_id', $group_id);
    }

    /**
     * 查看
     */
    public function index()
    {
       

        //设置过滤方法
        $this->request->filter(['strip_tags']);
        $zi = $this->request->request('zi','');
        $this->assignconfig('zi', $zi);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $where1 = [];
            if($this->group_id == 6){
                $where1['type'] = $this->admin['nickname'];
            }
            $list = $this->model
                ->where($where)
                ->where($where1)
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                $v['nickname'] = User::where(['id'=>$v['user_id']])->value('nickname');
                $v['mobile'] = User::where(['id'=>$v['user_id']])->value('mobile');
                $v['end_time'] = $v['end_time']?$v['end_time']:'';
                if (strpos($v['user_content'], 'https://') !== false) {
                    $v['user_content_1'] = $v['user_content'];
                    $v['user_content'] =  '查看链接';
                    $v['user_content_status'] = 1;
                }elseif(strpos($v['user_content'], 'http://') !== false){
                    $urls = explode('http://',$v['user_content']);
                    if(!empty($urls[1])){
                        $v['user_content'] = 'http://'.$urls[1];
                    }
                    $v['user_content_status'] = 2;
                }else{
                    $v['user_content_status'] = 0;
                }

                if($v['statistics_num'] == 0){
                    $v['statistics_num'] = '未回传';
                }
                
                if(empty($v['appuid']) && $v['user_content']){
                    $title = $v['user_content'];
                    $datas = [];
                    if (strpos($title, 'https://') !== false) {
                        $res = explode('?',$title);
                        if(empty($res[0])){
                            continue;                            
                        }
                        $datas = explode('/',$res[0]);
                    }elseif(strpos($title, 'http://') !== false){
                        $res = explode('http://',$title);
                        if(empty($res[1])){
                            continue;        
                        }
                        $res = explode('，',$res[1]);
                        $headers = get_headers('http://'.$res[0]); //获取重定向之后的url
                        foreach ($headers as $vs) {
                            if (strpos($vs, 'Location') !== false) {
                                $res = explode('?',$vs);
                                if(empty($res[0])){
                                    continue;
                                }
                                $datas = explode('/',$res[0]);
                            }
                        }
                    }
                    if(count($datas) < 4){
                        continue;
                    }
                    $res = DistributeTaskModer::where(['appuid'=>$datas[count($datas)-1]])->find();
                    $update = [];
                    if($res){
                        $update['is_repetition'] = 1;
                        $v['is_repetition'] = 1;
                    }
                    $update['appuid'] = $datas[count($datas)-1];
                    DistributeTaskModer::where(['id'=>$v['id']])->update($update);
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $statistics_num = 0;
        if($this->group_id == 6){
            $statistics_num =  $this->model->where(['type'=>$this->admin['nickname']])->sum('statistics_num');
        }
        $this->view->assign('statistics_num', $statistics_num);
        return $this->view->fetch();
    }


    /**
     * 批量更新
     *
     * @param $ids
     * @return void
     */
    public function multi($ids = null)
    {
 
        if (false === $this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $ids = $ids ?: $this->request->post('ids');
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }

        if (false === $this->request->has('params')) {
            $this->error(__('No rows were updated'));
        }
        parse_str($this->request->post('params'), $values);
        $values = $this->auth->isSuperAdmin() ? $values : array_intersect_key($values, array_flip(is_array($this->multiFields) ? $this->multiFields : explode(',', $this->multiFields)));
        if (empty($values)) {
            $this->error(__('You have no permission'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $count = 0;
        Db::startTrans();
        try {
            if($values['status'] == 0){
                //上架
                $list = $this->model->where($this->model->getPk(), 'in', $ids)->where(['status'=>-3])->select();
            }else{
                //下架
                $list = $this->model->where($this->model->getPk(), 'in', $ids)->where(['status'=>0])->select();
            }
            foreach ($list as $item) {
                $count += $item->allowField(true)->isUpdate(true)->save($values);
            }
            Db::commit();
        } catch (PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were updated'));
    }


    /**
     * 查看
     */
    public function user_index($ids = '')
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = $this->model
                ->where($where)
                ->where(['user_id'=>$ids])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                //判断是否已经开奖?
                $v['nickname'] = User::where(['id'=>$v['user_id']])->value('nickname');
                $v['end_time'] = $v['end_time']?$v['end_time']:'';
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    

    //接单人列表
    public function user_list()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = User::where($where)
                ->where(['is_task'=>1])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $k => &$v) {
                $v['task_sum'] = $this->model->where(['user_id'=>$v['id'],'status'=>['neq',0]])->count();
                $v['wc_task_sum'] = $this->model->where(['user_id'=>$v['id'],'status'=>3])->count();
                $v['withdraw_sum'] = Withdraw::where(['user_id'=>$v['id'],'status'=>['neq','rejected']])->sum('money');
                $v['handingfee_sum'] = Withdraw::where(['user_id'=>$v['id'],'status'=>['neq','rejected']])->sum('handingfee');
            }
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 浏览统计列表
     */
    public function statistics_list($ids = '')
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('name,url','',new DistributeStatistics());
            $list = DistributeStatistics::where($where)
                ->order($sort, $order)
                ->paginate($limit);
            // foreach ($list as &$v) {
            //     $v['status'] = 1;
            //     if($v['type'] == 2){
            //         //查询该笔提现状态
            //         $info = Withdraw::where(['money'=>$v['price']*-1,'user_id'=>$v['user_id']])->order('id desc')->find();
            //         if($info && $info['status'] == 'created'){
            //             $v['status'] = '2';
            //         }elseif($info && $info['status'] == 'rejected'){
            //             $v['status'] = '-1';
            //         }
            //     }
            // }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }
    /**
     * 添加浏览数量
     *
     * @return string
     * @throws \think\Exception
     */
    public function statistics_add($ids = null)
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if(!empty($params['add_time'])){
                $params['add_time'] = strtotime($params['add_time']);
            }else{
                $params['add_time'] = time();
            }
            $result = DistributeStatistics::insert($params);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

     /**
     * 删除
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function statistics_del($ids = null)
    {
        $row = DistributeStatistics::where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        $res = DistributeStatistics::where(['id'=>$ids])->delete();
        if (false === $res) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

    /**
     * 接单人财务明细
     */
    public function withdraw_list($ids = '')
    {
        $ids = $ids ? $ids : $this->request->post("ids");
        $this->assignconfig('ids', $ids);
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = DistributeTaskLog::where($where)
                ->where(['user_id'=>$ids])
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as &$v) {
                $v['status'] = 1;
                if($v['type'] == 2){
                    //查询该笔提现状态
                    $info = Withdraw::where(['money'=>$v['price']*-1,'user_id'=>$v['user_id']])->order('id desc')->find();
                    if($info && $info['status'] == 'created'){
                        $v['status'] = '2';
                    }elseif($info && $info['status'] == 'rejected'){
                        $v['status'] = '-1';
                    }
                }
            }
            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }


    /**
     * 删除团长
     *
     * @return string
     * @throws \think\Exception
     */
    public function detele_user_tz($id = null)
    {
        $status = $this->request->request('status');
        $result = false;
        Db::startTrans();
        try {
            $result = User::where(['id'=>$id])->update(['task_status'=>$status]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }
    

    /**
     * 指定团长
     *
     * @return string
     * @throws \think\Exception
     */
    public function user_list_add($ids = null)
    {
        if (false === $this->request->isPost()) {
            $user_list =  User::field("nickname,id")->where(['is_task'=>0,'status'=>1])->select();
            $this->view->assign('user_list', $user_list);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = User::where(['id'=>['in',$params['user_id']]])->update(['is_task'=>1,'task_time'=>time()]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

    /**
     * 人设编辑
     *
     * @return string
     * @throws \think\Exception
     */
    public function set_character_type($id = null)
    {
        $status = $this->request->request('status');
        $result = false;
        Db::startTrans();
        try {
            $result = User::where(['id'=>$id])->update(['character_type'=>$status]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            $user_list =  User::field("nickname,id")->where(['is_task'=>1])->select();
            $this->view->assign('user_list', $user_list);
            $PayConfig = PayConfig::where(['name'=>'task'])->value('value');
            $PayConfig = json_decode($PayConfig,true);
            $type_arr = explode(',',$PayConfig['type_arr']);
            $this->view->assign('type_arr', $type_arr);
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $result = false;
        Db::startTrans();
        try {
            //是否采用模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $title = explode('=',$params['title']);
            $content = explode('=',$params['content']);
            $imgs = explode(',',$params['imgs']);
            if($params['type'] == '电事聚小红书'){
                $imgs1 = explode(',',$params['imgs1']);
            }
            if(count($title) != count($content)  || count($imgs) < count($title)){
                $this->error('标题/内容/图片对应数量错误');
            }
            $product_id = empty($params['product_id']) ? 0 : $params['product_id'];
            foreach ($title as $k=>$v) {
                if($this->group_id == 6){
                    $arr = [
                        'add_time' => time(),
                        'title'=>$title[$k],
                        'content'=>$content[$k],
                        'imgs'=> count($title) > 1 ? $imgs[$k] : $params['imgs'],
                        'task_type'=>1,
                        'type'=>$this->admin['nickname'],
                        'category'=>$this->admin['nickname'],
                        'character_type'=>1,
                        'status'=>-3
                    ];
                }else{
                    if($params['type'] == '电事聚小红书'){
                        $arr = [
                            'add_time' => time(),
                            'title'=>$title[$k],
                            'content'=>$content[$k],
                            'imgs'=> count($title) > 1 ? $imgs[$k].','.$imgs1[$k] : $params['imgs'].','.$params['imgs1'],
                            'task_type'=>$params['task_type'] ? $params['task_type'] : 1,
                            'type'=>$params['type'] ,
                            'category'=>$params['category'] ,
                            'character_type'=>$params['character_type'] ? $params['character_type'] : 1,
                        ];
                    }else{
                        $arr = [
                            'add_time' => time(),
                            'title'=>$title[$k],
                            'content'=>$content[$k],
                            'imgs'=> count($title) > 1 ? $imgs[$k] : $params['imgs'],
                            'product_id'=>$product_id,
                            'task_type'=>$params['task_type'] ? $params['task_type'] : 1,
                            'type'=>$params['type'] ,
                            'category'=>$params['category'] ,
                            'character_type'=>$params['character_type'] ? $params['character_type'] : 1,
                        ];
                    }
                    
                }
                $result = DistributeTaskModer::insert($arr);
            }

            $ids = User::where(['is_task_subscription'=>1])->column('id');
            if($ids){
                $idss = DistributeTaskModer::where(['status'=>1,'user_id'=>['in',$ids]])->whereTime('receive_time', 'today')->column('user_id');
                $arr_ids = [];
                foreach ($ids as $v) {
                    if(!in_array($v,$idss)){
                        $arr_ids[] = $v;
                    }
                }
                if($arr_ids){
                    foreach ($arr_ids as $vs) {
                        //查看用户今天是否已经接单
                        $data = [
                            "thing1"=>["value"=>'余享新任务已更新'],
                            "time3"=>["value"=>date('Y-m-d H:i:s',time())]
                        ];
                        send_subscription($vs,'xF751UgAPsa4BajwBin-BU6lG1riuvJsNxNpIPGM28c','/subone/user/distribute_task',$data);
                    }
                }
            }
            // $list = User::where(['is_task_subscription'=>1])->select();
            // if($list){
            //     foreach ($list as $v) {
            //         //查看用户今天是否已经接单
            //         $data = [
            //             "thing1"=>["value"=>'余享新任务已更新'],
            //             "time3"=>["value"=>date('Y-m-d H:i:s',time())]
            //         ];
            //         send_subscription($v['id'],'xF751UgAPsa4BajwBin-BU6lG1riuvJsNxNpIPGM28c','/subone/user/distribute_task',$data);
            //         //User::where(['id'=>$v['id']])->update(['is_task_subscription'=>0]);
            //     }
            // }
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        
        $this->success();
    }



    
    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function product_add()
    {
        if (false === $this->request->isPost()) {
            $category=ProductCategory::where(array('pid'=>1,'status'=>'normal'))->order('weigh desc')->select();
            $this->view->assign('category_list', $category);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        if(empty($params['title'])){
            $this->error('标题不可为空');
        }
        if(empty($params['category_id'])){
            $this->error('请选择分类');
        }
        if($params['peisong'] == '0,1' && empty($params['weight'])){
            $this->error('请选择重量');
        }
        if(empty($params['imgs'])){
            $this->error('请选择图片');
        }
        $imgs_arr = explode(',',$params['imgs']);
        $params['video_img'] = $imgs_arr[0];

        $list = User::where(['virtual_status'=>1,'status'=>1])->select();
        if(!$list){
            $this->error('虚拟用户错误'); 
        }
        $UserAddress = $this->get_user($list);
        $params['user_id'] = $UserAddress['user_id'];
        $params['province'] = $UserAddress['province'];
        $params['city'] = $UserAddress['city'];
        $params['area'] = $UserAddress['district'];
        $params['name'] = $UserAddress['name'];
        $params['phone'] = $UserAddress['mobile'];
        $params['status'] = 1;
        $params['add_time'] = time();
        $params['want_count'] = rand(1,5);

        $fid = SArea::where(['name'=>['like','%'.$params['province'].'%']])->value('id');
        if($params['city'] != '市辖区'){
            $fid = SArea::where(['name'=>['like','%'.$params['city'].'%'],'fid'=>$fid])->value('id');
        }
        $info = SArea::where(['name'=>['like','%'.$params['area'].'%'],'fid'=>$fid])->find();
        $params['longitude'] = $info['lng'];
        $params['latitude'] = $info['lat'];
        if(!$params['longitude'] || !$params['latitude']){
			$params['longitude'] = '';
			$params['latitude'] = '';
		}
        $id = Product::insertGetId($params);
        if($id){
            $this->success('操作成功','',$id);
        }else{
            $this->error('操作失败');
        }
    }

    public function get_user($list)
    {
        $user = $list[rand(0,count($list)-1)];
        $UserAddress = UserAddress::where(['user_id'=>$user['id']])->order('is_default desc')->find();
        if(!$UserAddress){
            return $this->get_user($list);
        }else{
            return $UserAddress;
        }
    }
     /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->redirect('product_add');
            return;
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if (false === $this->request->isPost()) {
            if($row['end_time']){
                $row['end_time'] = date('Y-m-d H:i:s',$row['end_time']);
            }else{
                $row['end_time'] = '';
            }
            $Product = Product::where(['id'=>$row['product_id']])->find();
            $row['product_name'] = '';
            $row['product_status'] = '';
            if($Product){
                $row['product_name'] = $Product['title'];
                if($Product['is_sale'] == 1){
                    $row['product_status'] = '已售出';
                }else{
                    if($Product['status'] == 0){
                        $row['product_status'] = '待审核';
                    }elseif($Product['status'] == 1){
                        $row['product_status'] = '已上架';
                    }elseif($Product['status'] == -1){
                        $row['product_status'] = '已下架';
                    }elseif($Product['status'] == -2){
                        $row['product_status'] = '已删除';
                    }
                }
            }
            $this->view->assign('row', $row);
            $user_list =  User::field("nickname,id")->where(['is_task'=>1])->select();
            $this->view->assign('user_list', $user_list);
            $PayConfig = PayConfig::where(['name'=>'task'])->value('value');
            $PayConfig = json_decode($PayConfig,true);
            $type_arr = explode(',',$PayConfig['type_arr']);
            
            $this->view->assign('type_arr', $type_arr);

            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            if($row['end_time']){
                $row['end_time'] = date('Y-m-d H:i:s',$row['end_time']);
            }
            if($params['status'] == 1){
                //需要重新发布商品
                $arr = [
                    'add_time' => time(),
                    'title'=>$params['title'],
                    'content'=>$params['content'],
                    'imgs'=>$params['imgs'],
                    'product_id'=>$params['product_id'],
                    'type'=>$params['type']
                ];
                $result = DistributeTaskModer::insert($arr);
            }else{
                //编辑商品
                unset($params['status']);
                $result = $row->allowField(true)->save($params);
            }
            
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();
    }

     /**
     * 删除
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function del($ids = null)
    {
        $row = $this->model->where('id',$ids)->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }
        if($row['status'] == 0 || $row['status'] == -3){
            $res = $this->model->where(['id'=>$ids])->delete();
            if (false === $res) {
                $this->error(__('No rows were updated'));
            }
            $this->success();
        }else{
            $this->error('当前状态任务不可删除');
        }
        
    }

    //统计浏览数量
    public function statistics_update_status(){
        $id = $this->request->request('id',0);
        $statistics_num = $this->request->request('statistics_num','');
        $info = DistributeTaskModer::where(['id'=>$id,'status'=>3])->find();
        if(!$info){
            $this->error('数据错误');
        }
        Db::startTrans();
        try{
            $res = DistributeTaskModer::where(['id'=>$id])->update(['statistics_num'=>$statistics_num]);
            if(!$res){
                Db::rollback();
                $this->error('操作失败');
            }
            Db::commit();
            $this->success('操作成功');
        }catch (Exception $e) {
            Db::rollback();
            $this->error('操作失败');
        }
    }
    


    //更改状态
    public function update_status(){
        $id = $this->request->request('id',0);
        $status = $this->request->request('status','');
        $is_illegal = $this->request->request('is_illegal','');
        $remark = $this->request->request('remark','');
        if($is_illegal == 2){
            DistributeTaskModer::where(['id'=>$id])->update(['is_illegal'=>2]);
            $this->success('操作成功');
        }
        //上架
        if($status == 0){
            DistributeTaskModer::where(['id'=>$id])->update(['status'=>0]);
            $this->success('操作成功');
        }elseif($status == -3){//下架
            DistributeTaskModer::where(['id'=>$id])->update(['status'=>-3]);
            $this->success('操作成功');
        }
        $info = DistributeTaskModer::where(['id'=>$id,'status'=>2])->find();
        if(!$info){
            $this->error('数据错误');
        }
        $userInfo = User::where(['id'=>$info['user_id']])->find();
        Db::startTrans();
        try{
            //通过审核
            if($status == 1){
                //完成后分发佣金
                $info = DistributeTaskModer::where(['id'=>$id])->find();
                //查询佣金规则
                if($info['type'] == '电事聚小红书'){
                    $configWhere = ['name'=>'dianshiju'];
                }else{
                    $configWhere = ['name'=>'distribute'];
                }
                $config = Config::where($configWhere)->value('value');
                $config = json_decode($config,true);
                $price = 0;
                if(!empty($config['award'])){
                    $awardArr = $config['award'];
                    $priceArr = $config['price'];
                    foreach ($awardArr as $k=>$award_arr) {
                        if(count($award_arr) == 1){
                            if($info['statistics_num'] > $award_arr[0]){
                                $price = $priceArr[$k];
                            }
                        }else{
                            if($info['statistics_num'] >= $award_arr[0]  &&  $info['statistics_num'] <=  $award_arr[1]){
                                $price = $priceArr[$k];
                            }
                        }
                    }
                }else{
                    $price = $info['price'];
                }
                $res = DistributeTaskModer::where(['id'=>$id])->update(['status'=>3,'complete_time'=>time(),'price'=>$price]);
                if(!$res){
                    Db::rollback();
                    $this->error('操作失败');
                }
                //查看该用户是否是被邀请
                $DistributeTaskInvite = DistributeTaskInvite::where(['invite_id'=>$info['user_id'],'status'=>0])->find();
                if($DistributeTaskInvite){
                    DistributeTaskInvite::where(['id'=>$DistributeTaskInvite['id']])->update(['status'=>1,'price'=>2]);

                    $InviteUser = User::where(['id'=>$DistributeTaskInvite['user_id']])->find();
                    //记录佣金日志
                    $arr = [
                        'user_id'=>$InviteUser['id'],
                        'new_price'=>$InviteUser['task_price'],
                        'price'=>2,
                        'type'=>5,
                        'old_price'=>$InviteUser['task_price']+2,
                        'add_time'=>time()
                    ];
                    DistributeTaskLog::insert($arr);
                    User::where(['id'=>$InviteUser['id']])->update(['task_price'=>$InviteUser['task_price']+2]);
                }

                //通过审核后管理商户余额
                //set_shop_task_price($info['id'],2,$price);

                User::where(['id'=>$info['user_id']])->update(['task_price'=>$userInfo['task_price'] + $price]);
                //记录佣金日志
                $arr = [
                    'user_id'=>$info['user_id'],
                    'new_price'=>$userInfo['task_price'],
                    'price'=>$price,
                    'old_price'=>$userInfo['task_price']+$price,
                    'add_time'=>time()
                ];
                DistributeTaskLog::insert($arr);
                
                //发送短信
                send_mobile($userInfo['mobile'],'SMS_464185599');
            }else{
                $res = DistributeTaskModer::where(['id'=>$id])->update(['status'=>-1,'remark'=>$remark]);
                if(!$res){
                    Db::rollback();
                    $this->error('操作失败');
                }
                //发送短信
                send_mobile($userInfo['mobile'],'SMS_464210658');
            }
            Db::commit();
            $this->success('操作成功');
        }catch (Exception $e) {
            Db::rollback();
            $this->error('操作失败');
        }
    }



    /**
     * 查看
     */
    public function withdraw()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
            $list = Withdraw::alias('a')
                ->field("a.*,b.nickname,b.is_supervise")
                ->where($where)
                ->order($sort, $order)
                ->join("user b","b.id = a.user_id")
                ->paginate($limit);
           
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        return $this->view->fetch();
    }

    //更改状态
    public function withdraw_update_status(){
        $id = $this->request->request('id',0);
        $status = $this->request->request('status','');
        $remark = $this->request->request('remark','');
        $info = Withdraw::where(['id'=>$id])->find();
        if(!$info){
            $this->error('操作失败');
        }
        $user = User::where(['id'=>$info['user_id']])->find();
        if(!$user['openid']){
            $this->error('用户openid错误,操作失败');
        }
        //查询该用户提现金额流水是否正常
        $price_sum = DistributeTaskLog::where(['user_id'=>$user['id']])->sum('price');
        if($price_sum != $user['task_price'] && $status == 1){
            $this->error('用户佣金余额异常,操作失败');
        }
        Db::startTrans();
        try{
            //通过审核
            if($status == 1){
                //通过审核给用户打钱
                $WithdrawApi = new WithdrawApi();
                $data = ['out_detail_no'=>$info['orderid'],'transfer_amount'=>$info['money']*100,'transfer_remark'=>'用户提现','openid'=>$user['openid']];
                $resArr = $WithdrawApi->sendredpack([$data],'用户提现',$info['money']*100);
                if(!empty($resArr['batch_status']) &&  $resArr['batch_status'] =='ACCEPTED'){
                    //提现成功
                    $res = Withdraw::where(['id'=>$id])->update(['status'=>'successed','transactionid'=>$resArr['batch_id']]);
                    $arr = [
                        'type'=>'apply',
                        'pay_type'=>'wechat',
                        'order_id'=>$info['orderid'],
                        'out_trade_no'=>$info['orderid'],
                        'createtime'=>time(),
                        'amount'=>$info['money'],
                        'pay_amount'=>$info['money'],
                        'status'=>'success',
                        'pay_json'=>json_encode($resArr),
                        'payment_id'=>$resArr['out_batch_no'],
                        'transaction_id'=>$resArr['batch_id'],
                        'pay_time'=>time(),
                        'user_id'=>$user['id'],
                    ];
                    Payment::insert($arr);
                }else{
                    Db::rollback();
                    $arr = [
                        'type'=>'apply',
                        'pay_type'=>'wechat',
                        'order_id'=>$info['orderid'],
                        'out_trade_no'=>$info['orderid'],
                        'createtime'=>time(),
                        'amount'=>$info['money'],
                        'pay_amount'=>$info['money'],
                        'status'=>'fail',
                        'pay_json'=>json_encode($resArr),
                        'pay_time'=>time(),
                        'user_id'=>$user['id'],
                    ];
                    Payment::insert($arr);
                    if(!empty($resArr['message'])){
                        $this->error($resArr['message']);
                    }else{
                        $this->error('操作失败');
                    }
                }
            }else{
                $res = Withdraw::where(['id'=>$id])->update(['status'=>'rejected','remark'=>$remark]);
                if(!$res){
                    Db::rollback();
                    $this->error('操作失败');
                }
                //拒绝审核给返回用户金额
                $arr = [
                    'user_id'=>$user['id'],
                    'new_price'=>$user['task_price'],
                    'old_price'=>$user['task_price']+$info['money'],
                    'price'=>$info['money'],
                    'type'=>3,
                    'add_time'=>time()
                ];
                DistributeTaskLog::insert($arr);
                User::where(['id'=>$user['id']])->update(['task_price'=>$arr['old_price']]);
            }
            Db::commit();
            $this->success('操作成功');
        }catch (Exception $e) {
           Db::rollback();
           $this->error('操作失败');
        }
    }
    


    /**
     * 任务参数设置
     *
     * @return string
     * @throws \think\Exception
     */
    public function config()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);
        $result = false;
        Db::startTrans();
        try {
            $result = User::where(['id'=>['in',$params['user_id']]])->update(['is_task'=>1,'task_time'=>time()]);
            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('No rows were updated'));
        }
        $this->success();

    }

    //资金管理
    public function shop_fund()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            //查询该用户是否是商家
            if($this->group_id == 6){
                $shopwhere = ['name'=>$this->admin['nickname'],'status'=>1];
                $shop = Shop::where($shopwhere)->find();
                if($shop){
                    list($where, $sort, $order, $offset, $limit) = $this->buildparams('title');
                    $list = ShopPriceLog::where($where)
                        ->where(['shop_id'=>$shop['id']])
                        ->order($sort, $order)
                        ->paginate($limit);
                    $result = array("total" => $list->total(), "rows" => $list->items());
                }
            }

            if(!empty($result)){
                return json($result);
            }else{
                $result = array("total" => 0, "rows" => []);
                return json($result);
            }

            
        }
        return $this->view->fetch();
    }
    

}